package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysAttachment;
import com.ruoyi.system.mapper.SysAttachmentMapper;
import com.ruoyi.system.service.ISysAttachmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 附件管理Service业务层处理
 *
 * @author shuyan
 * @date 2021-01-13
 */
@Service
public class SysAttachmentServiceImpl extends ServiceImpl<SysAttachmentMapper, SysAttachment> implements ISysAttachmentService {

    @Override
    public List<SysAttachment> queryList(SysAttachment sysAttachment) {
        LambdaQueryWrapper<SysAttachment> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(sysAttachment.getBusinessType())) {
            lqw.eq(SysAttachment::getBusinessType, sysAttachment.getBusinessType());
        }
        if (StringUtils.isNotBlank(sysAttachment.getFileName())) {
            lqw.like(SysAttachment::getFileName, sysAttachment.getFileName());
        }
        if (StringUtils.isNotBlank(sysAttachment.getFileExt())) {
            lqw.eq(SysAttachment::getFileExt, sysAttachment.getFileExt());
        }
        if (StringUtils.isNotBlank(sysAttachment.getSaveNickName())) {
            lqw.like(SysAttachment::getSaveNickName, sysAttachment.getSaveNickName());
        }
        lqw.orderByDesc(SysAttachment::getSaveTime);
        return this.list(lqw);
    }

    @Override
    public boolean saveAttachment(SysAttachment sysAttachment, MultipartFile file) {
        //设置操作人
        Date saveTime = new Date();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        sysAttachment.setSaveTime(saveTime).setSaveUserName(user.getUserName()).setSaveNickName(user.getNickName());
        //文件非空时设置上传信息
        if (file != null && !file.isEmpty()) {
            //文件上传路径
            String uploadPath = Constants.ATTACHMENT_PREFIX_PATH + DateUtil.format(saveTime, "/yyyy-MM/dd");
            //转存文件
            String originalFilename = file.getOriginalFilename();
            sysAttachment.setFileName(originalFilename);
            String fileExt = FileUtil.extName(originalFilename);
            sysAttachment.setFileExt(fileExt);
            String fileName = saveTime.getTime() + RandomUtil.randomString(6) + "." + fileExt;
            try {
                String fileSaveUrl = RuoYiConfig.getProfile() + uploadPath;
                FileUtil.mkdir(fileSaveUrl);
                file.transferTo(new File(fileSaveUrl, fileName));
            } catch (IOException e) {
                log.error("附件管理", e);
                throw new ServiceException("文件接收失败,失败原因: " + e.getMessage());
            }
            sysAttachment.setRealName(fileName);
            sysAttachment.setFilePath(uploadPath + "/" + fileName);
        }
        return saveOrUpdate(sysAttachment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeAttachment(List<Long> ids) {
        for (Long id : ids) {
            SysAttachment attachment = getById(id);
            //删除文件
            String filePath = attachment.getFilePath();
            FileUtil.del(RuoYiConfig.getProfile() + filePath);
        }
        return removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delAttachmentByFilePath(String filePath) {
        LambdaQueryWrapper<SysAttachment> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysAttachment::getFilePath, filePath);
        boolean success = remove(lqw);
        FileUtil.del(RuoYiConfig.getProfile() + filePath);
        return success;
    }

    @Override
    public SysAttachment getAttachmentByFilePath(String filePath) {
        return lambdaQuery().eq(SysAttachment::getFilePath, filePath).one();
    }
}
